/**
 * @author: gao
 * @create-date: 2025/3/1 15:24
 */
class TreeNode{
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode() {}

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public String tree2str(TreeNode root){
        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }

    public void tree2strChild(TreeNode root,StringBuilder stringBuilder){
        if(root == null){
            return;
        }
        stringBuilder.append(root.val);

        //判断根的左子树
        if(root.left != null){
            stringBuilder.append("(");
            tree2strChild(root.left,stringBuilder);//递归左树
            stringBuilder.append(")");//左树走完，右括号闭合
        }else {
            if(root.right == null){
                return;//因为4结点走完，返回2结点，这里本身就会加一个")"
            }else {
                stringBuilder.append("()");
            }
        }

        //判断根的右子树
        if(root.right != null){
            stringBuilder.append("(");
            tree2strChild(root.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }
}